<template>
    <div>
        <div style="display: flex; position: relative;">
            <div style="flex: 1;">
                <!-- <div style="border: 1px solid #8492a6; border-radius: 4px; margin-bottom: 15px;">
                    <el-select v-model="keywords" filterable remote reserve-keyword placeholder="请输入关键词"
                        :remote-method="remoteMethod" :loading="loading" :clearable="true" size="mini"
                        @change="currentSelect" style="width: 100%">
                        <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item"
                            class="one-text">
                            <span style="float: left">{{ item.name }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{
                                item.district
                            }}</span>
                        </el-option>
                    </el-select>
                </div> -->
                <div v-if="position_index == 0" id="container1" class="container"></div>
                <div v-if="position_index == 1" id="container2" class="container"></div>
                <div v-if="position_index == 2" id="container3" class="container"></div>
            </div>
            <!-- <div class="info-box">
                纬度：{{ form.lat }}
                <br />
                经度：{{ form.lng }}
                <p>详细地址：{{ form.address }}</p>
            </div> -->
        </div>
        <!-- <div style="margin: 50px 30px 0 0; text-align: right;">
            <el-button type="primary" @click="closeMap">确 定</el-button>
        </div> -->
    </div>
</template>

<script>



import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
    // 安全密钥
    securityJsCode: localStorage.getItem('map_secret'),
};
export default {
    name: "TestIndex",
    props: {
        lat: {
            type: Number,
        },
        lng: {
            type: Number,
        },
        position_index: {
            type: Number,
        },
        address: {
            type: String,
        },
        currentIndex: {
            type: Number,
        },
        isflag: {
            type: Number,
        },
        isIndex: {
            type: Number,
        }
    },
    data () {
        return {
            // 地图实例数组
            maps: [null, null, null],
            // 标记点数组
            markers: [null, null, null],
            // 地址逆解析数组
            geoCoders: [null, null, null],
            // 搜索提示数组
            AutoCompletes: [null, null, null],
            // 搜索关键字
            keywords: "",
            // 位置信息
            forms: [
                { lng: "", lat: "", address: "", adcode: "", position_index: 0 },
                { lng: "", lat: "", address: "", adcode: "", position_index: 1 },
                { lng: "", lat: "", address: "", adcode: "", position_index: 2 }
            ],
            // 搜索节流阀
            loading: false,
            // 搜索提示信息
            options: [],
        };
    },
    methods: {
        // 关闭模态框
        closeMap () {
            this.$emit('childData', this.forms[this.position_index], this.position_index);
            this.keywords = '';
        },
        initMap (index) {
            // console.log('this.position_index', this.position_index);
            console.log('我被调用了');

            // this.forms[index].position_index = this.position_index;
            this.forms[index].address = this.address;
            this.forms[index].lat = this.lat || 39.9042; // 使用默认位置（例如北京）
            this.forms[index].lng = this.lng || 116.4074; // 使用默认位置（例如北京）
            AMapLoader.load({
                key: localStorage.getItem('map_key'),
                version: "2.0",
                plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
            })
                .then((AMap) => {
                    this.maps[index] = new AMap.Map(`container${index + 1}`, {
                        viewMode: "2D",
                        zoom: 14,
                        center: [this.forms[index].lng, this.forms[index].lat],
                    });
                    this.markers[index] = new AMap.Marker({
                        map: this.maps[index],
                        position: [this.forms[index].lng, this.forms[index].lat],
                        title: "工厂",
                    });
                    this.maps[index].add(this.markers[index]);
                    this.geoCoders[index] = new AMap.Geocoder({
                        city: "全国",
                        radius: 1000,
                    });
                    this.AutoCompletes[index] = new AMap.AutoComplete({ city: "全国" });
                    this.maps[index].on("click", (e) => {
                        this.forms[index].lng = e.lnglat.lng;
                        this.forms[index].lat = e.lnglat.lat;
                        // this.lat = e.lnglat.lat
                        // this.lng = e.lnglat.lng
                        // console.log(this.lat, '我是外层坐标');
                        // console.log(this.forms[index].lat, '我是内层坐标');
                        // console.log(this.isflag, '我是固定坐标');

                        // this.isflag = 1

                        this.removeMarker(index);
                        this.setMapMarker(index);
                    });
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        setMapMarker (index) {
            this.maps[index].setFitView();
            this.markers[index] = new AMap.Marker({
                map: this.maps[index],
                position: [this.forms[index].lng, this.forms[index].lat],
            });
            this.toGeoCoder(index);
            this.maps[index].setFitView();
            this.maps[index].add(this.markers[index]);
        },
        removeMarker (index) {
            if (this.markers[index]) {
                this.maps[index].remove(this.markers[index]);
            }
        },
        toGeoCoder (index) {
            let lnglat = [this.forms[index].lng, this.forms[index].lat];
            this.geoCoders[index].getAddress(lnglat, (status, result) => {
                if (status === "complete" && result.regeocode) {
                    this.forms[index].address = result.regeocode.formattedAddress;
                }
                this.$emit('childData', this.forms[index]);
                this.keywords = '';
            });
        },
        beforeDestroy () {
            // 销毁对应的地图实例
            // if (this.maps[this.position_index]) {
            //     this.maps[this.position_index].destroy(); // 假设 AMap.Map 有 destroy 方法
            //     this.maps[this.position_index] = null; // 清理引用
            // }
            if (this.maps[index]) {

                // this.position_index = null
                this.maps[index].destroy(); // 销毁地图实例
                this.maps[index] = null; // 清空地图实例
                this.markers[index] = null; // 清空标记
                this.geoCoders[index] = null; // 清空地址解析器
                this.AutoCompletes[index] = null; // 清空搜索提示
            }
        },
        destroyMap (index, length) {
            // 交换第一个和第二个对象的指定属性
            if (length == 3 && index == 0) {
                // let forms = this.forms
                // console.log('333333333333');

                // [forms[0].lng, forms[1].lng] = [forms[1].lng, forms[0].lng];
                // [forms[0].lat, forms[1].lat] = [forms[1].lat, forms[0].lat];
                // [forms[0].address, forms[1].address] = [forms[1].address, forms[0].address];
                // console.log(forms, '222222222222222222');
                // this.forms = forms
                // this.initMap(index + 2);
            } else {
                this.initMap(index);
            }

        }
    },
    mounted () {
        // console.log('this.position_indexTwo', this.position_index);

        this.initMap(this.position_index);
    },
    watch: {
        // lat () {
        //     this.initMap(this.currentIndex);
        // },
        isIndex () {
            // this.destroyMap(this.isIndex)
            this.initMap(this.currentIndex);
            // this.isIndex = null
        }
    }
};
</script>

<style>
.container {
    /* width: 700px; */
    /* flex: 1; */
    height: 300px;
}


.info-box {
    background-color: #fff;
    position: absolute;
    top: 60px;
    right: 20px;
    padding: 15px;
    border-radius: 10px;
}
</style>